import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useLikeStore = defineStore(
    'like',
    () => {
        const likeImgs = ref<string[]>([])
        const userName = ref<string>('')

        const getImgs = () => {
            uniCloud.callFunction({
                name: 'getImgs',
                data: { user: userName.value },
                success: (res) => {
                    const arr: any = []
                    res.result.data.forEach((item: any) => {
                        arr.push(item.url)
                    })
                    likeImgs.value = arr
                }
            })
        }
        const addImg = (url: string) => {
            if (!likeImgs.value.includes(url)) likeImgs.value.push(url)
            uniCloud.callFunction({
                name: 'addImg',
                data: { user: userName.value, url: url },
                success: (res) => {
                    console.log(res);
                }
            })
        }
        const delImg = (url: string) => {
            likeImgs.value = likeImgs.value.filter((item) => item !== url)
            uniCloud.callFunction({
                name: 'delImg',
                data: { user: userName.value, url: url },
                success: (res) => {
                    console.log(res);
                }
            })
        }
        return {
            userName,
            likeImgs,
            getImgs,
            addImg,
            delImg
        }
    },
    // TODO: 持久化
    {
        // 网页端
        // persist: true,
        // 小程序配置
        persist: {
            storage: {
                getItem(key) {
                    return uni.getStorageSync(key);
                },
                setItem(key, value) {
                    uni.setStorageSync(key, value);
                },
            }
        }
    },
)
